<template>
  <div class="front-header">
    <div class="header-container">
      <!-- Logo区域（点击跳转首页） -->
      <div class="logo-area" @click="router.push('/')">
        <el-icon><ShoppingCart /></el-icon>
        <span>农销通</span>
      </div>

      <!-- 导航菜单（路由模式） -->
      <el-menu
          mode="horizontal"
          :router="true"
          :default-active="activePath"
          class="nav-menu"
      >
        <el-menu-item index="/">首页</el-menu-item>
        <el-menu-item index="/products">全部商品</el-menu-item>
        <el-menu-item index="/seckill">秒杀商品</el-menu-item>
        <el-menu-item index="/cart">购物车</el-menu-item>
        <el-menu-item index="/order">我的订单</el-menu-item>
        <el-menu-item index="/articles" class="nav-item">农业资讯</el-menu-item>
      </el-menu>

      <!-- 右侧搜索与用户操作区 -->
      <div class="right-section">
        <!-- 搜索框 -->
        <div class="search-box">
          <el-input
              v-model="searchKey"
              placeholder="搜索商品..."
              @keyup.enter="handleSearch"
          class="search-input"
          >
          <!-- Vue3 具名插槽新语法：#prefix 替代 slot="prefix" -->
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>

          </el-input>
        </div>

        <!-- 用户操作区 -->
        <div class="user-actions">
          <!-- 未登录状态 -->
          <template v-if="!isLoggedIn">
            <el-button type="primary" text @click="goToLogin">
              <el-icon><User /></el-icon>
              <span>登录</span>
            </el-button>
          </template>

          <!-- 已登录状态（下拉菜单） -->
          <template v-else>
            <!-- 消息入口 -->
            <el-badge :value="unreadCount" :max="99" :hidden="unreadCount === 0" class="message-badge">
              <el-button type="primary" link @click="goToMessage">
                <el-icon><ChatDotRound /></el-icon>
                <span>消息</span>
              </el-button>
            </el-badge>

            <el-dropdown trigger="click">
              <div class="user-info">
                <span class="username">{{ userInfo.username }}</span>
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </div>
              <!-- Vue3 具名插槽新语法：#dropdown 替代 slot="dropdown" -->
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="goToUserCenter">  <!-- Vue3移除.native修饰符 -->
                    <el-icon><User /></el-icon> 个人中心
                  </el-dropdown-item>
                  <el-dropdown-item @click="goToFavorite">
                    <el-icon><Star /></el-icon> 我的收藏
                  </el-dropdown-item>
                  <el-dropdown-item @click="goToMessage">
                    <el-icon><ChatDotRound /></el-icon> 消息管理
                  </el-dropdown-item>
                  <el-dropdown-item @click="logout">
                    <el-icon><SwitchButton /></el-icon> 退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// 1. 引入Vue3核心API
import { ref, computed, onMounted, defineOptions } from 'vue'
// 2. 引入Vue3路由API（替代Vue2的this.$router/$route）
import { useRouter, useRoute } from 'vue-router'
// 3. 引入Element Plus组件（消息提示，替代Vue2的this.$message）
import { ElMessage, ElMenu, ElMenuItem, ElInput, ElButton, ElDropdown, ElDropdownMenu, ElDropdownItem, ElIcon } from 'element-plus'
import { ShoppingCart, Search, User, ArrowDown, Star, SwitchButton } from '@element-plus/icons-vue'
// 4. 定义组件名（Vue3 <script setup> 需显式声明）
defineOptions({
  name: 'FrontHeader'
})

// 5. 创建响应式变量（替代Vue2的data选项）
const searchKey = ref('')        // 搜索关键词
const isLoggedIn = ref(false)   // 登录状态
const userInfo = ref({})        // 用户信息
const unreadCount = ref(0)      // 未读消息数

// 6. 获取路由实例（替代Vue2的this.$router/$route）
const router = useRouter()
const route = useRoute()

// 7. 计算属性（替代Vue2的computed选项）：当前激活的路由路径
const activePath = computed(() => {
  return route.fullPath  // 修复：Vue3通过route直接获取当前路由，不需要route.currentRoute
})

// 8. 检查登录状态（原methods中的函数）
const checkLoginStatus = () => {
  const storedUser = localStorage.getItem('frontUser')
  if (storedUser) {
    isLoggedIn.value = true          // ref变量需通过.value修改
    userInfo.value = JSON.parse(storedUser)
    // 获取未读消息数
    getUnreadCount()
  }
}

// 获取未读消息数
const getUnreadCount = () => {
  // 这里应该调用后端接口获取未读消息数
  // 示例：
  // request.get(`/message/unread/count/${userInfo.value.id}`).then(response => {
  //   if (response.code === '0') {
  //     unreadCount.value = response.data
  //   }
  // })
}

// 9. 跳转登录页
const goToLogin = () => {
  router.push('/login')
}

// 10. 跳转个人中心
const goToUserCenter = () => {
  router.push('/user-center')
}

// 11. 跳转我的收藏（需登录校验）
const goToFavorite = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')  // 替代Vue2的this.$message.warning
    router.push('/login')
    return
  }
  router.push('/favorite')
}

// 跳转消息页面
const goToMessage = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')  // 替代Vue2的this.$message.warning
    router.push('/login')
    return
  }
  router.push('/message1')
}

// 12. 退出登录（清除缓存+状态重置）
const logout = () => {
  // 清除localStorage缓存
  localStorage.removeItem('token')
  localStorage.removeItem('frontUser')
  // 重置响应式状态
  isLoggedIn.value = false
  userInfo.value = {}
  unreadCount.value = 0
  // 提示+跳转首页+刷新页面
  ElMessage.success('已退出登录')  // 替代Vue2的this.$message.success
  router.push('/')
  window.location.reload()  // 保留原刷新逻辑（确保状态完全重置）
}

// 13. 搜索功能（跳转搜索页并携带关键词）
const handleSearch = () => {
  const keyword = searchKey.value.trim()
  if (!keyword) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  // 携带query参数跳转搜索页
  router.push({
    path: '/search',
    query: { keyword }
  })
  // 清空搜索框
  searchKey.value = ''
}

// 14. 跳转后台（原注释代码，保留逻辑）
const goToAdmin = () => {
  const userMenuList = localStorage.getItem('userMenuList')
  const backUser = localStorage.getItem('backUser')
  if (!userMenuList || !backUser) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  router.push('/showView')
}

// 15. 生命周期钩子（替代Vue2的created）
// 组件挂载时检查登录状态
onMounted(() => {
  checkLoginStatus()
  // 监听storage事件，当其他标签页登录/退出时同步状态
  window.addEventListener('storage', checkLoginStatus)
})

// 15. 组件卸载前执行（替代Vue2的beforeDestroy生命周期）
// onUnmounted(() => {
//   window.removeEventListener('storage', checkLoginStatus)
// })
</script>

<style scoped>
/* 样式完全保留原逻辑，仅确保Vue3样式穿透兼容性 */
.front-header {
  background-color: #ffffff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
  background: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  height: 55px;
  position: relative;
  overflow: hidden;
}

.front-header::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom,
  rgba(255, 255, 255, 0.98),
  #fff
  );
  backdrop-filter: blur(10px);
  z-index: -1;
}

.front-header::before {
  content: '';
  position: absolute;
  inset: 0;
  background-image:
      radial-gradient(circle at 0% 0%, rgba(103, 194, 58, 0.03) 0%, transparent 50%),
      radial-gradient(circle at 100% 0%, rgba(103, 194, 58, 0.03) 0%, transparent 50%),
      radial-gradient(circle at 50% 50%, rgba(103, 194, 58, 0.01) 0%, transparent 50%),
      linear-gradient(90deg, rgba(103, 194, 58, 0.01) 0%, rgba(103, 194, 58, 0.02) 50%, rgba(103, 194, 58, 0.01) 100%);
  opacity: 0.8;
  z-index: -1;
}

.header-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  height: 100%;
  display: flex;
  align-items: center;
  height: 60px;
  padding: 0 20px;
}

.logo-area {
  display: flex;
  align-items: center;
  font-size: 20px;
  font-weight: bold;
  color: #3AB777;
  cursor: pointer;
  color: #67C23A;
  font-size: 18px;
  font-weight: 600;
  padding: 4px 8px;
  border-radius: 6px;
  transition: all 0.3s ease;
  background: linear-gradient(120deg,
  rgba(103, 194, 58, 0.05) 0%,
  rgba(103, 194, 58, 0.1) 50%,
  rgba(103, 194, 58, 0.05) 100%
  );
  position: relative;
  overflow: hidden;
}

.logo-area::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.2) 0%, transparent 60%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.logo-area:hover {
  background: linear-gradient(120deg,
  rgba(103, 194, 58, 0.1) 0%,
  rgba(103, 194, 58, 0.15) 50%,
  rgba(103, 194, 58, 0.1) 100%
  );
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.1);
}

.logo-area:hover::before {
  opacity: 1;
}

.logo-area :deep(.el-icon) {
  font-size: 22px;
  background: linear-gradient(45deg, #67C23A, #85ce61);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  filter: drop-shadow(0 1px 2px rgba(103, 194, 58, 0.2));
}

.nav-menu {
  border: none;
  background: transparent;
  height: 55px;
  line-height: 55px;
  flex: 1;
  position: relative;
  z-index: 1;
  backdrop-filter: blur(4px);
}

/* 修复样式穿透语法错误 */
:deep(.el-menu--horizontal > .el-menu-item) {
  height: 55px;
  line-height: 55px;
  padding: 0 16px;
  font-size: 16px;
  border: none !important;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

:deep(.el-menu--horizontal > .el-menu-item:hover) {
  background: linear-gradient(to right, transparent, rgba(103, 194, 58, 0.05), transparent);
}

:deep(.el-menu--horizontal > .el-menu-item.is-active) {
  color: #67C23A;
  font-weight: 500;
  background: linear-gradient(to right, transparent, rgba(103, 194, 58, 0.08), transparent);
}

.right-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-box {
  width: 220px;
}

:deep(.search-input .el-input__inner) {
  height: 32px;
  line-height: 32px;
  border-radius: 16px;
  background: #f5f7fa;
  border: 1px solid transparent;
  padding-left: 35px;
  font-size: 13px;
  transition: all 0.3s ease;
}

:deep(.search-input .el-input__inner:focus) {
  background: #fff;
  border-color: #67C23A;
  box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.1);
}

:deep(.search-input .el-input__prefix) {
  left: 12px;
  display: flex;
  align-items: center;
  height: 100%;
}

:deep(.search-input .el-input__prefix .el-icon) {
  font-size: 15px;
  color: #909399;
}

:deep(.search-input .el-input__inner:focus + .el-input__prefix .el-icon) {
  color: #67C23A;
}

.user-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-dropdown-menu) {
  padding: 6px;
  border-radius: 8px;
  border: none;
  box-shadow: 0 3px 15px rgba(0, 0, 0, 0.1);
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  padding: 10px 16px;
  border-radius: 6px;
  margin: 2px 0;
  line-height: 1;
}

:deep(.el-dropdown-menu__item .el-icon) {
  font-size: 15px;
  color: #606266;
}

:deep(.el-dropdown-menu__item:hover) {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

:deep(.el-dropdown-menu__item:hover .el-icon) {
  color: #67C23A;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.user-info:hover {
  background: rgba(103, 194, 58, 0.1);
}

.user-info :deep(.el-icon) {
  font-size: 12px;
  margin-left: 4px;
  transition: transform 0.3s ease;
}

.user-info:hover :deep(.el-icon) {
  transform: rotate(180deg);
}

.username {
  font-size: 13px;
  color: #606266;
}

/* 响应式布局（完全保留原逻辑） */
@media (max-width: 1200px) {
  .header-container {
    padding: 0 16px;
    gap: 16px;
  }

  .search-box {
    width: 180px;
  }

  :deep(.el-menu--horizontal > .el-menu-item) {
    padding: 0 12px;
  }
}

@media (max-width: 992px) {
  .search-box {
    width: 160px;
  }

  .action-btn span {
    display: none;
  }

  .action-btn {
    padding: 8px;
  }

  .action-btn i {
    margin: 0;
  }
}
</style>